using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using JGSY.CMS.LowCode.Platform.Application.DTOs.Monitoring;
using JGSY.CMS.LowCode.Platform.Application.Interfaces.Monitoring;
using System.ComponentModel.DataAnnotations;

namespace JGSY.CMS.LowCode.Platform.Controllers;

/***
🎯 MonitoringController 的真实功能
📊 前端数据采集控制器 (不是服务器监控)
这个控制器的主要功能是：

🌐 浏览器端数据收集
[HttpPost("performance")] - 接收浏览器回传的性能指标数据

页面加载时间、资源加载时间
前端性能指标 (如 First Paint, LCP 等)
会话ID、页面URL、时间戳等
[HttpPost("errors")] - 接收浏览器回传的前端错误日志

JavaScript 错误、资源加载错误
错误堆栈、发生页面、用户会话等
[HttpPost("interactions")] - 接收浏览器回传的用户交互数据

点击事件、页面跳转、表单提交
用户行为轨迹、交互时间等
🔑 关键特征
[AllowAnonymous] - 允许匿名访问，方便前端监控脚本调用
数据验证 - 验证 SessionId、PageUrl、Timestamp 等前端字段
批量处理 - 支持批量上报性能指标数据
📈 仪表板功能
[HttpGet("dashboard")] - 提供监控仪表板数据查询
[HttpGet("errors/summary")] - 错误汇总统计
[HttpGet("sessions/{sessionId}")] - 会话详情查看
🔍 与服务器监控的区别
功能类型	MonitoringController	服务器监控
数据来源	🌐 浏览器/前端	🖥️ 服务器系统
监控对象	👤 用户体验、前端性能	⚙️ CPU、内存、磁盘
访问权限	匿名访问	需要授权
数据类型	页面性能、JS错误、用户交互	系统资源、进程状态
调用方式	前端JS主动上报	服务器被动采集
所以您的理解完全正确：MonitoringController 是用于收集浏览器回传的前端监控数据，而不是服务器系统监控！

**/


/// <summary>
/// 监控API控制器
/// 提供性能指标、错误日志、用户交互的数据收集和监控仪表板数据查询功能
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class MonitoringController : ControllerBase
{
    private readonly IMonitoringService _monitoringService;
    private readonly ILogger<MonitoringController> _logger;

    public MonitoringController(IMonitoringService monitoringService, ILogger<MonitoringController> logger)
    {
        _monitoringService = monitoringService;
        _logger = logger;
    }

    /// <summary>
    /// 批量记录性能指标
    /// </summary>
    /// <param name="metrics">性能指标列表</param>
    /// <returns>记录结果</returns>
    [HttpPost("performance")]
    [AllowAnonymous] // 允许匿名访问以便前端监控脚本调用
    public async Task<IActionResult> RecordPerformance([FromBody] List<PerformanceMetricDto> metrics)
    {
        try
        {
            // 数据验证
            if (metrics == null || !metrics.Any())
            {
                return BadRequest(new { error = "No metrics provided", code = "MON001" });
            }

            // 验证必填字段
            var invalidMetrics = metrics.Where(m => 
                string.IsNullOrEmpty(m.SessionId) || 
                string.IsNullOrEmpty(m.MetricName) || 
                string.IsNullOrEmpty(m.PageUrl) ||
                m.Timestamp <= 0
            ).ToList();

            if (invalidMetrics.Any())
            {
                return BadRequest(new { 
                    error = "Invalid metrics data", 
                    code = "MON002",
                    details = "SessionId, MetricName, PageUrl and Timestamp are required"
                });
            }

            // 记录指标
            var success = await _monitoringService.RecordPerformanceMetricsAsync(metrics);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    recorded = metrics.Count, 
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record metrics", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordPerformance endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录错误日志
    /// </summary>
    /// <param name="error">错误信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("errors")]
    [AllowAnonymous] // 允许匿名访问以便前端监控脚本调用
    public async Task<IActionResult> RecordError([FromBody] ErrorLogDto error)
    {
        try
        {
            // 数据验证
            if (error == null)
            {
                return BadRequest(new { error = "No error data provided", code = "MON001" });
            }

            // 验证必填字段
            if (string.IsNullOrEmpty(error.SessionId) || 
                string.IsNullOrEmpty(error.ErrorType) || 
                string.IsNullOrEmpty(error.PageUrl) ||
                error.Timestamp <= 0)
            {
                return BadRequest(new { 
                    error = "Invalid error data", 
                    code = "MON002",
                    details = "SessionId, ErrorType, PageUrl and Timestamp are required"
                });
            }

            // 记录错误
            var success = await _monitoringService.RecordErrorAsync(error);
            
            if (success)
            {
                return Ok(new { success = true });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record error", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordError endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录用户交互
    /// </summary>
    /// <param name="interaction">交互信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("interactions")]
    [AllowAnonymous] // 允许匿名访问以便前端监控脚本调用
    public async Task<IActionResult> RecordInteraction([FromBody] UserInteractionDto interaction)
    {
        try
        {
            // 数据验证
            if (interaction == null)
            {
                return BadRequest(new { error = "No interaction data provided", code = "MON001" });
            }

            // 验证必填字段
            if (string.IsNullOrEmpty(interaction.SessionId) || 
                string.IsNullOrEmpty(interaction.InteractionType) || 
                string.IsNullOrEmpty(interaction.PageUrl) ||
                interaction.Timestamp <= 0)
            {
                return BadRequest(new { 
                    error = "Invalid interaction data", 
                    code = "MON002",
                    details = "SessionId, InteractionType, PageUrl and Timestamp are required"
                });
            }

            // 记录交互
            var success = await _monitoringService.RecordUserInteractionAsync(interaction);
            
            if (success)
            {
                return Ok(new { success = true });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record interaction", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordInteraction endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取监控仪表板数据
    /// </summary>
    /// <param name="startDate">开始日期（ISO格式）</param>
    /// <param name="endDate">结束日期（ISO格式）</param>
    /// <returns>仪表板数据</returns>
    [HttpGet("dashboard")]
    [Authorize] // 需要授权访问
    public async Task<IActionResult> GetDashboard([FromQuery] string? startDate = null, [FromQuery] string? endDate = null)
    {
        try
        {
            DateTime? start = null;
            DateTime? end = null;

            // 解析日期参数
            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out var parsedStart))
            {
                start = parsedStart;
            }

            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out var parsedEnd))
            {
                end = parsedEnd;
            }

            var dashboard = await _monitoringService.GetDashboardDataAsync(start, end);
            return Ok(dashboard);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetDashboard endpoint");
            return StatusCode(500, new { error = "Failed to retrieve dashboard data", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取错误汇总信息
    /// </summary>
    /// <param name="limit">限制数量</param>
    /// <returns>错误汇总列表</returns>
    [HttpGet("errors/summary")]
    [Authorize] // 需要授权访问
    public async Task<IActionResult> GetErrorSummary([FromQuery] int limit = 50)
    {
        try
        {
            if (limit <= 0 || limit > 1000)
            {
                return BadRequest(new { error = "Limit must be between 1 and 1000", code = "MON002" });
            }

            var errors = await _monitoringService.GetErrorSummaryAsync(limit);
            return Ok(errors);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetErrorSummary endpoint");
            return StatusCode(500, new { error = "Failed to retrieve error summary", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取会话详情
    /// </summary>
    /// <param name="sessionId">会话ID</param>
    /// <returns>会话详情</returns>
    [HttpGet("sessions/{sessionId}")]
    [Authorize] // 需要授权访问
    public async Task<IActionResult> GetSession(string sessionId)
    {
        try
        {
            if (string.IsNullOrEmpty(sessionId))
            {
                return BadRequest(new { error = "Session ID is required", code = "MON002" });
            }

            var session = await _monitoringService.GetSessionDetailAsync(sessionId);
            
            if (string.IsNullOrEmpty(session.SessionId))
            {
                return NotFound(new { error = "Session not found", code = "MON404" });
            }
            
            return Ok(session);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error in GetSession endpoint for session {sessionId}");
            return StatusCode(500, new { error = "Failed to retrieve session", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取性能趋势数据
    /// </summary>
    /// <param name="metricName">指标名称</param>
    /// <param name="hours">小时数</param>
    /// <returns>趋势数据</returns>
    [HttpGet("trends/{metricName}")]
    [Authorize] // 需要授权访问
    public async Task<IActionResult> GetPerformanceTrends(string metricName, [FromQuery] int hours = 24)
    {
        try
        {
            if (string.IsNullOrEmpty(metricName))
            {
                return BadRequest(new { error = "Metric name is required", code = "MON002" });
            }

            if (hours <= 0 || hours > 168) // 最多一周
            {
                return BadRequest(new { error = "Hours must be between 1 and 168", code = "MON002" });
            }

            var trends = await _monitoringService.GetPerformanceTrendsAsync(metricName, hours);
            return Ok(trends);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error in GetPerformanceTrends endpoint for metric {metricName}");
            return StatusCode(500, new { error = "Failed to retrieve performance trends", code = "MON003" });
        }
    }

    /// <summary>
    /// 清理过期数据（管理员功能）
    /// </summary>
    /// <param name="retentionDays">数据保留天数</param>
    /// <returns>清理结果</returns>
    [HttpPost("cleanup")]
    [Authorize(Roles = "Admin")] // 仅管理员可以访问
    public async Task<IActionResult> CleanupExpiredData([FromQuery] int retentionDays = 90)
    {
        try
        {
            if (retentionDays < 7 || retentionDays > 365)
            {
                return BadRequest(new { error = "Retention days must be between 7 and 365", code = "MON002" });
            }

            var cleanedCount = await _monitoringService.CleanupExpiredDataAsync(retentionDays);
            
            return Ok(new { 
                success = true, 
                cleanedRecords = cleanedCount,
                retentionDays = retentionDays
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in CleanupExpiredData endpoint");
            return StatusCode(500, new { error = "Failed to cleanup expired data", code = "MON003" });
        }
    }

    // ============================================================
    // 性能监控API - Core Web Vitals 专用端点
    // ============================================================

    /// <summary>
    /// 记录 Core Web Vitals 专用指标
    /// 专门处理 LCP、FID、CLS、FCP、TTFB 等核心性能指标
    /// </summary>
    /// <param name="vitalsMetrics">Core Web Vitals 指标列表</param>
    /// <returns>记录结果</returns>
    [HttpPost("performance/vitals")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordCoreWebVitals([FromBody] List<VitalsMetricDto> vitalsMetrics)
    {
        try
        {
            // 数据验证
            if (vitalsMetrics == null || !vitalsMetrics.Any())
            {
                return BadRequest(new { error = "No vitals metrics provided", code = "MON001" });
            }

            // 验证指标名称是否为 Core Web Vitals
            var validVitals = new[] { "LCP", "FID", "CLS", "FCP", "TTFB" };
            var invalidMetrics = vitalsMetrics.Where(m => !validVitals.Contains(m.MetricName)).ToList();

            if (invalidMetrics.Any())
            {
                return BadRequest(new { 
                    error = "Invalid vitals metric names", 
                    code = "MON002",
                    details = $"Valid metrics are: {string.Join(", ", validVitals)}",
                    invalidMetrics = invalidMetrics.Select(m => m.MetricName)
                });
            }

            // 转换为通用性能指标格式
            var performanceMetrics = vitalsMetrics.Select(v => new PerformanceMetricDto
            {
                SessionId = v.SessionId,
                UserId = v.UserId,
                MetricName = v.MetricName,
                MetricValue = v.MetricValue,
                MetricRating = v.MetricRating,
                PageUrl = v.PageUrl,
                UserAgent = v.UserAgent,
                BrowserName = v.BrowserName,
                DeviceType = v.DeviceType,
                Timestamp = v.Timestamp
            }).ToList();

            var success = await _monitoringService.RecordPerformanceMetricsAsync(performanceMetrics);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    recorded = vitalsMetrics.Count, 
                    metricsType = "core-web-vitals",
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record vitals metrics", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordCoreWebVitals endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录自定义性能指标
    /// 用于业务相关的自定义性能指标，如登录耗时、表单提交耗时等
    /// </summary>
    /// <param name="customMetrics">自定义指标列表</param>
    /// <returns>记录结果</returns>
    [HttpPost("performance/custom")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordCustomMetrics([FromBody] List<CustomMetricDto> customMetrics)
    {
        try
        {
            if (customMetrics == null || !customMetrics.Any())
            {
                return BadRequest(new { error = "No custom metrics provided", code = "MON001" });
            }

            // 转换为通用性能指标格式
            var performanceMetrics = customMetrics.Select(c => new PerformanceMetricDto
            {
                SessionId = c.SessionId,
                UserId = c.UserId,
                MetricName = c.MetricName,
                MetricValue = c.MetricValue,
                MetricRating = c.Category, // 使用 Category 作为 Rating
                PageUrl = c.PageUrl,
                UserAgent = c.UserAgent,
                BrowserName = c.BrowserName,
                DeviceType = c.DeviceType,
                Timestamp = c.Timestamp
            }).ToList();

            var success = await _monitoringService.RecordPerformanceMetricsAsync(performanceMetrics);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    recorded = customMetrics.Count, 
                    metricsType = "custom-performance",
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record custom metrics", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordCustomMetrics endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    // ============================================================
    // 错误监控API - 专用错误端点
    // ============================================================

    /// <summary>
    /// 记录 JavaScript 错误
    /// 专门处理 JavaScript 运行时错误，包括语法错误、类型错误等
    /// </summary>
    /// <param name="jsError">JavaScript 错误信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("errors/javascript")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordJavaScriptError([FromBody] JavaScriptErrorDto jsError)
    {
        try
        {
            if (jsError == null)
            {
                return BadRequest(new { error = "No JavaScript error data provided", code = "MON001" });
            }

            // 转换为通用错误格式
            var errorLog = new ErrorLogDto
            {
                SessionId = jsError.SessionId,
                UserId = jsError.UserId,
                ErrorType = "javascript-error",
                ErrorMessage = jsError.ErrorMessage,
                ErrorStack = jsError.ErrorStack,
                ErrorFilename = jsError.ErrorFilename,
                ErrorLineNumber = jsError.ErrorLineNumber,
                ErrorColumnNumber = jsError.ErrorColumnNumber,
                PageUrl = jsError.PageUrl,
                UserAgent = jsError.UserAgent,
                Severity = "high", // JavaScript 错误默认为高严重性
                Timestamp = jsError.Timestamp
            };

            var success = await _monitoringService.RecordErrorAsync(errorLog);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    errorType = "javascript-error",
                    severity = "high"
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record JavaScript error", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordJavaScriptError endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录 Promise 拒绝错误
    /// 专门处理未捕获的 Promise 拒绝异常
    /// </summary>
    /// <param name="promiseError">Promise 拒绝错误信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("errors/promise")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordPromiseRejection([FromBody] PromiseRejectionDto promiseError)
    {
        try
        {
            if (promiseError == null)
            {
                return BadRequest(new { error = "No promise rejection data provided", code = "MON001" });
            }

            // 转换为通用错误格式
            var errorLog = new ErrorLogDto
            {
                SessionId = promiseError.SessionId,
                UserId = promiseError.UserId,
                ErrorType = "promise-rejection",
                ErrorMessage = promiseError.ReasonMessage,
                ErrorStack = promiseError.ReasonStack,
                PageUrl = promiseError.PageUrl,
                UserAgent = promiseError.UserAgent,
                Severity = "medium", // Promise 拒绝默认为中等严重性
                Timestamp = promiseError.Timestamp
            };

            var success = await _monitoringService.RecordErrorAsync(errorLog);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    errorType = "promise-rejection",
                    severity = "medium"
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record promise rejection", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordPromiseRejection endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录网络错误
    /// 专门处理 HTTP 请求失败、超时、中断等网络相关错误
    /// </summary>
    /// <param name="networkError">网络错误信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("errors/network")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordNetworkError([FromBody] NetworkErrorDto networkError)
    {
        try
        {
            if (networkError == null)
            {
                return BadRequest(new { error = "No network error data provided", code = "MON001" });
            }

            // 转换为通用错误格式
            var errorLog = new ErrorLogDto
            {
                SessionId = networkError.SessionId,
                UserId = networkError.UserId,
                ErrorType = "network-error",
                ErrorMessage = $"{networkError.HttpMethod} {networkError.RequestUrl} - {networkError.ErrorType}: {networkError.ErrorMessage}",
                PageUrl = networkError.PageUrl,
                UserAgent = networkError.UserAgent,
                Severity = networkError.StatusCode >= 500 ? "high" : "medium",
                Timestamp = networkError.Timestamp
            };

            var success = await _monitoringService.RecordErrorAsync(errorLog);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    errorType = "network-error",
                    statusCode = networkError.StatusCode,
                    severity = errorLog.Severity
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record network error", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordNetworkError endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    // ============================================================
    // 用户行为监控API - 专用交互端点
    // ============================================================

    /// <summary>
    /// 记录页面访问事件
    /// 专门处理页面浏览、路由切换等页面访问行为
    /// </summary>
    /// <param name="pageView">页面访问信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("interactions/pageviews")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordPageView([FromBody] PageViewDto pageView)
    {
        try
        {
            if (pageView == null)
            {
                return BadRequest(new { error = "No page view data provided", code = "MON001" });
            }

            // 转换为通用交互格式
            var interaction = new UserInteractionDto
            {
                SessionId = pageView.SessionId,
                InteractionType = "page_view",
                PageUrl = pageView.PageUrl,
                TargetElement = pageView.PageTitle,
                Timestamp = pageView.Timestamp
            };

            var success = await _monitoringService.RecordUserInteractionAsync(interaction);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    interactionType = "page_view",
                    pageUrl = pageView.PageUrl
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record page view", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordPageView endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录点击事件
    /// 专门处理用户点击交互，包括按钮、链接、表单元素等
    /// </summary>
    /// <param name="clickEvent">点击事件信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("interactions/clicks")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordClickEvent([FromBody] ClickEventDto clickEvent)
    {
        try
        {
            if (clickEvent == null)
            {
                return BadRequest(new { error = "No click event data provided", code = "MON001" });
            }

            // 转换为通用交互格式
            var interaction = new UserInteractionDto
            {
                SessionId = clickEvent.SessionId,
                InteractionType = "click",
                PageUrl = clickEvent.PageUrl,
                TargetElement = clickEvent.TargetElement,
                ElementText = clickEvent.ElementText,
                Timestamp = clickEvent.Timestamp
            };

            var success = await _monitoringService.RecordUserInteractionAsync(interaction);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    interactionType = "click",
                    targetElement = clickEvent.TargetElement
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record click event", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordClickEvent endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录滚动深度事件
    /// 专门处理页面滚动行为分析
    /// </summary>
    /// <param name="scrollEvent">滚动深度信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("interactions/scroll")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordScrollDepth([FromBody] ScrollDepthDto scrollEvent)
    {
        try
        {
            if (scrollEvent == null)
            {
                return BadRequest(new { error = "No scroll data provided", code = "MON001" });
            }

            // 转换为通用交互格式
            var interaction = new UserInteractionDto
            {
                SessionId = scrollEvent.SessionId,
                InteractionType = "scroll",
                PageUrl = scrollEvent.PageUrl,
                ScrollDepth = scrollEvent.ScrollDepthPercent,
                Duration = scrollEvent.TimeToScroll,
                Timestamp = scrollEvent.Timestamp
            };

            var success = await _monitoringService.RecordUserInteractionAsync(interaction);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    interactionType = "scroll",
                    scrollDepth = $"{scrollEvent.ScrollDepthPercent}%"
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record scroll event", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordScrollDepth endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 记录表单交互事件
    /// 专门处理表单填写、提交、验证等交互行为
    /// </summary>
    /// <param name="formInteraction">表单交互信息</param>
    /// <returns>记录结果</returns>
    [HttpPost("interactions/forms")]
    [AllowAnonymous]
    public async Task<IActionResult> RecordFormInteraction([FromBody] FormInteractionDto formInteraction)
    {
        try
        {
            if (formInteraction == null)
            {
                return BadRequest(new { error = "No form interaction data provided", code = "MON001" });
            }

            // 转换为通用交互格式
            var interaction = new UserInteractionDto
            {
                SessionId = formInteraction.SessionId,
                InteractionType = formInteraction.InteractionType,
                PageUrl = formInteraction.PageUrl,
                TargetElement = formInteraction.FormId ?? formInteraction.FormName,
                ElementText = formInteraction.FieldName,
                Duration = formInteraction.TimeSpent,
                Timestamp = formInteraction.Timestamp
            };

            var success = await _monitoringService.RecordUserInteractionAsync(interaction);
            
            if (success)
            {
                return Ok(new { 
                    success = true, 
                    interactionType = formInteraction.InteractionType,
                    formId = formInteraction.FormId,
                    fieldName = formInteraction.FieldName
                });
            }
            else
            {
                return StatusCode(500, new { error = "Failed to record form interaction", code = "MON003" });
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in RecordFormInteraction endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    // ============================================================
    // 批量处理API
    // ============================================================

    /// <summary>
    /// 批量处理监控数据
    /// 一次性处理多种类型的监控数据，提高数据传输效率
    /// </summary>
    /// <param name="batchData">批量数据</param>
    /// <returns>批量处理结果</returns>
    [HttpPost("batch")]
    [AllowAnonymous]
    public async Task<IActionResult> ProcessBatchData([FromBody] BatchDataDto batchData)
    {
        try
        {
            if (batchData == null)
            {
                return BadRequest(new { error = "No batch data provided", code = "MON001" });
            }

            var results = new Dictionary<string, object>();
            var totalProcessed = 0;
            var errors = new List<string>();

            // 处理 Core Web Vitals
            if (batchData.VitalsMetrics?.Any() == true)
            {
                try
                {
                    var performanceMetrics = batchData.VitalsMetrics.Select(v => new PerformanceMetricDto
                    {
                        SessionId = v.SessionId,
                        UserId = v.UserId,
                        MetricName = v.MetricName,
                        MetricValue = v.MetricValue,
                        MetricRating = v.MetricRating,
                        PageUrl = v.PageUrl,
                        UserAgent = v.UserAgent,
                        BrowserName = v.BrowserName,
                        DeviceType = v.DeviceType,
                        Timestamp = v.Timestamp
                    }).ToList();

                    var success = await _monitoringService.RecordPerformanceMetricsAsync(performanceMetrics);
                    if (success)
                    {
                        results["vitalsMetrics"] = new { processed = batchData.VitalsMetrics.Count, status = "success" };
                        totalProcessed += batchData.VitalsMetrics.Count;
                    }
                    else
                    {
                        errors.Add("Failed to process vitals metrics");
                    }
                }
                catch (Exception ex)
                {
                    errors.Add($"Vitals metrics error: {ex.Message}");
                    _logger.LogError(ex, "Error processing vitals metrics in batch");
                }
            }

            // 处理自定义性能指标
            if (batchData.CustomMetrics?.Any() == true)
            {
                try
                {
                    var performanceMetrics = batchData.CustomMetrics.Select(c => new PerformanceMetricDto
                    {
                        SessionId = c.SessionId,
                        UserId = c.UserId,
                        MetricName = c.MetricName,
                        MetricValue = c.MetricValue,
                        MetricRating = c.Category,
                        PageUrl = c.PageUrl,
                        UserAgent = c.UserAgent,
                        BrowserName = c.BrowserName,
                        DeviceType = c.DeviceType,
                        Timestamp = c.Timestamp
                    }).ToList();

                    var success = await _monitoringService.RecordPerformanceMetricsAsync(performanceMetrics);
                    if (success)
                    {
                        results["customMetrics"] = new { processed = batchData.CustomMetrics.Count, status = "success" };
                        totalProcessed += batchData.CustomMetrics.Count;
                    }
                    else
                    {
                        errors.Add("Failed to process custom metrics");
                    }
                }
                catch (Exception ex)
                {
                    errors.Add($"Custom metrics error: {ex.Message}");
                    _logger.LogError(ex, "Error processing custom metrics in batch");
                }
            }

            // 处理通用错误
            if (batchData.GeneralErrors?.Any() == true)
            {
                try
                {
                    foreach (var error in batchData.GeneralErrors)
                    {
                        await _monitoringService.RecordErrorAsync(error);
                    }
                    results["generalErrors"] = new { processed = batchData.GeneralErrors.Count, status = "success" };
                    totalProcessed += batchData.GeneralErrors.Count;
                }
                catch (Exception ex)
                {
                    errors.Add($"General errors error: {ex.Message}");
                    _logger.LogError(ex, "Error processing general errors in batch");
                }
            }

            // 处理用户交互
            if (batchData.GeneralInteractions?.Any() == true)
            {
                try
                {
                    foreach (var interaction in batchData.GeneralInteractions)
                    {
                        await _monitoringService.RecordUserInteractionAsync(interaction);
                    }
                    results["interactions"] = new { processed = batchData.GeneralInteractions.Count, status = "success" };
                    totalProcessed += batchData.GeneralInteractions.Count;
                }
                catch (Exception ex)
                {
                    errors.Add($"Interactions error: {ex.Message}");
                    _logger.LogError(ex, "Error processing interactions in batch");
                }
            }

            return Ok(new 
            { 
                success = true,
                batchId = batchData.BatchId,
                totalProcessed = totalProcessed,
                results = results,
                errors = errors.Any() ? errors : null,
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in ProcessBatchData endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    // ============================================================
    // 仪表板API - 专用数据查询端点
    // ============================================================

    /// <summary>
    /// 获取监控统计数据
    /// 返回核心监控指标的统计摘要
    /// </summary>
    /// <param name="startDate">开始日期</param>
    /// <param name="endDate">结束日期</param>
    /// <returns>统计数据</returns>
    [HttpGet("dashboard/stats")]
    [Authorize]
    public async Task<IActionResult> GetMonitoringStats([FromQuery] string? startDate = null, [FromQuery] string? endDate = null)
    {
        try
        {
            DateTime? start = null;
            DateTime? end = null;

            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out var parsedStart))
            {
                start = parsedStart;
            }

            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out var parsedEnd))
            {
                end = parsedEnd;
            }

            var dashboard = await _monitoringService.GetDashboardDataAsync(start, end);
            
            // 返回统计摘要
            return Ok(new 
            {
                summary = new 
                {
                    activeSessions = dashboard.Summary.ActiveSessions,
                    totalErrors = dashboard.Summary.TotalErrors,
                    avgLCP = dashboard.Summary.AvgLCP,
                    avgFID = dashboard.Summary.AvgFID,
                    avgCLS = dashboard.Summary.AvgCLS,
                    avgFCP = dashboard.Summary.AvgFCP,
                    avgTTFB = dashboard.Summary.AvgTTFB
                },
                dateRange = new 
                {
                    startDate = start?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
                    endDate = end?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.ToString("yyyy-MM-dd")
                },
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetMonitoringStats endpoint");
            return StatusCode(500, new { error = "Failed to retrieve monitoring stats", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取性能监控报表数据
    /// 返回详细的性能指标趋势和分析数据
    /// </summary>
    /// <param name="startDate">开始日期</param>
    /// <param name="endDate">结束日期</param>
    /// <param name="granularity">数据粒度：hour, day, week</param>
    /// <returns>性能报表数据</returns>
    [HttpGet("dashboard/performance")]
    [Authorize]
    public async Task<IActionResult> GetPerformanceReport(
        [FromQuery] string? startDate = null, 
        [FromQuery] string? endDate = null,
        [FromQuery] string granularity = "day")
    {
        try
        {
            DateTime? start = null;
            DateTime? end = null;

            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out var parsedStart))
            {
                start = parsedStart;
            }

            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out var parsedEnd))
            {
                end = parsedEnd;
            }

            var dashboard = await _monitoringService.GetDashboardDataAsync(start, end);
            
            return Ok(new 
            {
                performance = new 
                {
                    coreWebVitals = new 
                    {
                        avgLCP = dashboard.Summary.AvgLCP,
                        avgFID = dashboard.Summary.AvgFID,
                        avgCLS = dashboard.Summary.AvgCLS,
                        avgFCP = dashboard.Summary.AvgFCP,
                        avgTTFB = dashboard.Summary.AvgTTFB
                    },
                    trends = dashboard.PerformanceTrends,
                    distribution = new 
                    {
                        // 基于当前数据结构，先使用空数据，后续可扩展
                        good = new Dictionary<string, int>(),
                        needsImprovement = new Dictionary<string, int>(),
                        poor = new Dictionary<string, int>()
                    }
                },
                metadata = new 
                {
                    granularity = granularity,
                    dateRange = new 
                    {
                        startDate = start?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
                        endDate = end?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.ToString("yyyy-MM-dd")
                    },
                    dataPoints = dashboard.PerformanceTrends?.Count ?? 0
                },
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetPerformanceReport endpoint");
            return StatusCode(500, new { error = "Failed to retrieve performance report", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取错误监控报表数据
    /// 返回详细的错误统计和分析数据
    /// </summary>
    /// <param name="startDate">开始日期</param>
    /// <param name="endDate">结束日期</param>
    /// <param name="severity">错误严重级别过滤</param>
    /// <returns>错误报表数据</returns>
    [HttpGet("dashboard/errors")]
    [Authorize]
    public async Task<IActionResult> GetErrorReport(
        [FromQuery] string? startDate = null, 
        [FromQuery] string? endDate = null,
        [FromQuery] string? severity = null)
    {
        try
        {
            DateTime? start = null;
            DateTime? end = null;

            if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out var parsedStart))
            {
                start = parsedStart;
            }

            if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out var parsedEnd))
            {
                end = parsedEnd;
            }

            var dashboard = await _monitoringService.GetDashboardDataAsync(start, end);
            var errorSummary = await _monitoringService.GetErrorSummaryAsync(100);
            
            // 按严重级别过滤
            if (!string.IsNullOrEmpty(severity))
            {
                errorSummary = errorSummary.Where(e => e.Severity?.Equals(severity, StringComparison.OrdinalIgnoreCase) == true).ToList();
            }

            return Ok(new 
            {
                errors = new 
                {
                    totalCount = dashboard.Summary.TotalErrors,
                    byType = dashboard.ErrorStatistics.ByType,
                    bySeverity = errorSummary.GroupBy(e => e.Severity).ToDictionary(g => g.Key ?? "unknown", g => g.Count()),
                    recentErrors = errorSummary.Take(20).Select(e => new 
                    {
                        e.ErrorType,
                        e.ErrorMessage,
                        e.Severity,
                        e.PageUrl,
                        timestamp = e.LastOccurred,
                        occurrences = e.Count
                    }),
                    trends = dashboard.ErrorStatistics.RecentErrors // 使用最近错误作为趋势，后续可扩展专用趋势数据
                },
                metadata = new 
                {
                    severityFilter = severity,
                    dateRange = new 
                    {
                        startDate = start?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
                        endDate = end?.ToString("yyyy-MM-dd") ?? DateTime.UtcNow.ToString("yyyy-MM-dd")
                    }
                },
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetErrorReport endpoint");
            return StatusCode(500, new { error = "Failed to retrieve error report", code = "MON003" });
        }
    }

    /// <summary>
    /// 健康检查端点
    /// </summary>
    /// <returns>系统状态</returns>
    [HttpGet("health")]
    [AllowAnonymous]
    public IActionResult HealthCheck()
    {
        return Ok(new { 
            status = "healthy", 
            timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
            version = "2.0.0",
            endpoints = new 
            {
                performance = new[]
                {
                    "POST /api/monitoring/performance",
                    "POST /api/monitoring/performance/vitals",
                    "POST /api/monitoring/performance/custom"
                },
                errors = new[]
                {
                    "POST /api/monitoring/errors",
                    "POST /api/monitoring/errors/javascript",
                    "POST /api/monitoring/errors/promise",
                    "POST /api/monitoring/errors/network"
                },
                interactions = new[]
                {
                    "POST /api/monitoring/interactions",
                    "POST /api/monitoring/interactions/pageviews",
                    "POST /api/monitoring/interactions/clicks",
                    "POST /api/monitoring/interactions/scroll",
                    "POST /api/monitoring/interactions/forms"
                },
                dashboard = new[]
                {
                    "GET /api/monitoring/dashboard",
                    "GET /api/monitoring/dashboard/stats",
                    "GET /api/monitoring/dashboard/performance",
                    "GET /api/monitoring/dashboard/errors",
                    "GET /api/monitoring/dashboard/pages",
                    "GET /api/monitoring/dashboard/users",
                    "GET /api/monitoring/dashboard/realtime"
                },
                batch = new[]
                {
                    "POST /api/monitoring/batch",
                    "POST /api/monitoring/bulk"
                },
                management = new[]
                {
                    "GET /api/monitoring/health",
                    "GET /api/monitoring/config",
                    "PUT /api/monitoring/config",
                    "GET /api/monitoring/status",
                    "POST /api/monitoring/cleanup",
                    "GET /api/monitoring/sessions/{sessionId}",
                    "GET /api/monitoring/trends/{metricName}",
                    "GET /api/monitoring/errors/summary"
                }
            }
        });
    }

    /// <summary>
    /// 大批量数据处理
    /// </summary>
    /// <param name="bulkData">大批量数据</param>
    /// <returns>处理结果</returns>
    [HttpPost("bulk")]
    [AllowAnonymous]
    public async Task<IActionResult> BulkProcess([FromBody] BulkDataDto bulkData)
    {
        try
        {
            if (bulkData == null || !bulkData.DataItems.Any())
            {
                return BadRequest(new { error = "No bulk data provided", code = "MON001" });
            }

            var success = await _monitoringService.ProcessBulkDataAsync(bulkData);
            
            return Ok(new { 
                success, 
                processed = bulkData.DataItems.Count, 
                operation = bulkData.OperationType,
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in BulkProcess endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取页面分析数据
    /// </summary>
    /// <param name="timeRange">时间范围</param>
    /// <param name="page">指定页面</param>
    /// <returns>页面分析数据</returns>
    [HttpGet("dashboard/pages")]
    [AllowAnonymous]
    public async Task<IActionResult> GetDashboardPages([FromQuery] string timeRange = "24h", [FromQuery] string? page = null)
    {
        try
        {
            var pagesData = await _monitoringService.GetPageAnalysisAsync(timeRange, page);
            return Ok(pagesData);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetDashboardPages endpoint");
            return StatusCode(500, new { error = "Failed to retrieve page analysis data", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取用户行为分析数据
    /// </summary>
    /// <param name="userId">用户ID</param>
    /// <param name="timeRange">时间范围</param>
    /// <returns>用户分析数据</returns>
    [HttpGet("dashboard/users")]
    [AllowAnonymous]
    public async Task<IActionResult> GetDashboardUsers([FromQuery] string? userId = null, [FromQuery] string timeRange = "24h")
    {
        try
        {
            var usersData = await _monitoringService.GetUserAnalysisAsync(userId, timeRange);
            return Ok(usersData);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetDashboardUsers endpoint");
            return StatusCode(500, new { error = "Failed to retrieve user analysis data", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取实时监控数据
    /// </summary>
    /// <returns>实时数据</returns>
    [HttpGet("dashboard/realtime")]
    [AllowAnonymous]
    public async Task<IActionResult> GetDashboardRealtime()
    {
        try
        {
            var realtimeData = await _monitoringService.GetRealtimeDataAsync();
            return Ok(realtimeData);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetDashboardRealtime endpoint");
            return StatusCode(500, new { error = "Failed to retrieve realtime data", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取监控配置
    /// </summary>
    /// <returns>监控配置</returns>
    [HttpGet("config")]
    [AllowAnonymous]
    public async Task<IActionResult> GetMonitoringConfig()
    {
        try
        {
            var config = await _monitoringService.GetMonitoringConfigAsync();
            return Ok(config);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetMonitoringConfig endpoint");
            return StatusCode(500, new { error = "Failed to retrieve monitoring config", code = "MON003" });
        }
    }

    /// <summary>
    /// 更新监控配置
    /// </summary>
    /// <param name="config">监控配置</param>
    /// <returns>更新结果</returns>
    [HttpPut("config")]
    public async Task<IActionResult> UpdateMonitoringConfig([FromBody] MonitoringConfigDto config)
    {
        try
        {
            if (config == null)
            {
                return BadRequest(new { error = "No config data provided", code = "MON001" });
            }

            var success = await _monitoringService.UpdateMonitoringConfigAsync(config);
            
            return Ok(new { 
                success, 
                message = success ? "Configuration updated successfully" : "Failed to update configuration",
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in UpdateMonitoringConfig endpoint");
            return StatusCode(500, new { error = "Internal server error", code = "MON003" });
        }
    }

    /// <summary>
    /// 获取系统状态
    /// </summary>
    /// <returns>系统状态</returns>
    [HttpGet("status")]
    [AllowAnonymous]
    public async Task<IActionResult> GetSystemStatus()
    {
        try
        {
            var status = await _monitoringService.GetSystemStatusAsync();
            return Ok(status);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in GetSystemStatus endpoint");
            return StatusCode(500, new { error = "Failed to retrieve system status", code = "MON003" });
        }
    }
}
